/**
 * 
 */
package org.compiere.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;

import extend.org.compiere.utils.Util;

/**
 * @author V.Sokolov
 *
 */
public class MBPMPaymentMonth extends X_BPM_PaymentMonth {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3586701511762722936L;

	/**
	 * @param ctx
	 */
	public MBPMPaymentMonth(Properties ctx) {
		super(ctx);
	}

	/**
	 * @param ctx
	 * @param BPM_PaymentMonth_ID
	 * @param trxName
	 */
	public MBPMPaymentMonth(Properties ctx, int BPM_PaymentMonth_ID,
			String trxName) {
		super(ctx, BPM_PaymentMonth_ID, trxName);
	}

	/**
	 * @param ctx
	 * @param rs
	 * @param trxName
	 */
	public MBPMPaymentMonth(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}
	
	/*
	 */
	@Override
	protected boolean beforeSave(boolean newRecord) {
		
		int i = 0;
		if(!isDefault()) i++;
		
		String errmsg = "";
		if(getCountDefault()-i >= 1)
			errmsg = "Is Default > 1";
		Util.checkErrMsg(errmsg);
		
		return true;
	}
	
	public static int getDefault(){
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;		
		int result = 0;
		
		String sql = "SELECT "+I_BPM_PaymentMonth.COLUMNNAME_BPM_PaymentMonth_ID+" FROM "+I_BPM_PaymentMonth.Table_Name+" \n" +
					 "WHERE "+I_BPM_PaymentMonth.COLUMNNAME_IsDefault+"='Y'";
		try
		{
			pstmt = DB.prepareStatement(sql,null);
			rs = pstmt.executeQuery();	
					
			if(rs.next ())
				return result = rs.getInt(1);
		}
		catch (SQLException e)
		{
			CLogger.get().log(Level.INFO, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		
		if(result == 0)
			throw new AdempiereException("Оплата по умолчанию не найдна");
		
		return 0;
	}
	
	private int getCountDefault(){
		
		List<MBPMPaymentMonth> list = new Query(Env.getCtx(), I_BPM_PaymentMonth.Table_Name, I_BPM_PaymentMonth.COLUMNNAME_IsDefault+"=?", null)
		.setParameters("Y")
		.setOnlyActiveRecords(true)
		.list();
		
		return list.size();
	}
	
}
